using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Win32SDK;
using System.Runtime.InteropServices;
using System.Threading;

namespace TaskSystemClient
{
    public delegate void ScheduledOperation();
    public sealed class UIThread
    {
        private static Queue<ScheduledOperation> operationQueue = new Queue<ScheduledOperation>();
        private UIThread()
        {
        }

        public static void AddScheduledOperation(ScheduledOperation op)
        {
            lock (operationQueue)
            {
                operationQueue.Enqueue(op);
            }
        }
        public static bool AppMessageLoopCallback()
        {
            ProcessOperationQueue();
            return true;
        }
        public class MyMessageFilter: IMessageFilter
        {
            bool IMessageFilter.PreFilterMessage(ref Message m)
            {
                //if (m.Msg == Win32SDK.Constants.WM_TIMER)
                //{
                    ProcessOperationQueue();
                //}
                return false;
            }
        };
        public static void Run(Form form)
        {
            MyMessageFilter mmf = new MyMessageFilter();
            //Application.RegisterMessageLoop(AppMessageLoopCallback);
            Application.AddMessageFilter(mmf);
            Application.Run(form);
            //while (!form.IsDisposed)
            //{
            //    Application.DoEvents();
            //    Thread.Sleep(1);
            //}
        }

        private static void ProcessOperationQueue()
        {
            if (operationQueue.Count != 0)
            {
                lock (operationQueue)
                {
                    ScheduledOperation op = operationQueue.Dequeue();
                    try
                    {
                        op();
                    }
                    catch (Exception e)
                    {
                        GameEditor.Common.Dialogs.ShowException(e);
                    }
                }
            }
        }
    }
}
